﻿using AutoMapper;
using B.S.BasicData.Api.Read.Applications.Command;
using B.S.BasicData.Api.Read.Dto;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;

namespace B.S.BasicData.Api.Read.Applications.CommandHandler
{
    public class RoleQueryCommandHandler : IRequestHandler<RoleQueryCommand, ApiResult<List<PermissonDto>>>
    {
        private readonly IBaseRepository<Role>roleRepository;
        private readonly IBaseRepository<Permissons> permissonsRepository;
        private readonly IBaseRepository<RolePermissons> rolepermissonsRepository;
        private readonly IMapper mapper;

        public RoleQueryCommandHandler(IBaseRepository<Role> roleRepository, IBaseRepository<Permissons> permissonsRepository, IMapper mapper, IBaseRepository<RolePermissons> rolepermissonsRepository)
        {
            this.roleRepository = roleRepository;
            this.permissonsRepository = permissonsRepository;
            this.mapper = mapper;
            this.rolepermissonsRepository = rolepermissonsRepository;
        }

        public Task<ApiResult<List<PermissonDto>>> Handle(RoleQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<PermissonDto>> result = new ApiResult<List<PermissonDto>>();
            result.Code = ApiEnum.Success;
            result.Message = "角色权限列表展示成功";
            var query = roleRepository.GetAll();

            var data=mapper.Map<List<PermissonDto>>(query);
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                data = data.Where(x => x.RoleName.Contains(request.RoleName)).ToList();
            }
            foreach ( var item in data )
            {
                var permissionIds = rolepermissonsRepository.GetAll().Where(x => x.RoleId == item.RoleId).Select(x => x.PermissonId).ToList();
                var permissionName = permissonsRepository.GetAll().Where(x => permissionIds.Contains(x.PermissonId)).Select(x => x.PermissonName).ToList();
                item.PermissonId = permissionIds;
                item.PermissonName = permissionName;
                result.data = data;
              

            }
          
            return Task.FromResult(result);
            //var list = from a in roleRepository.GetAll()
            //           join b in permissonsRepository.GetAll() on a.PermissonId equals b.PermissonId.ToString()

            //           select new PermissonDto
            //           {

            //               PermissonName = b.PermissonName,
            //               PermissonValue = b.PermissonValue,
            //               PerseId = b.PerseId,
            //               RoleId = a.RoleId,
            //               RoleName = a.RoleName,
            //               CreateTime = a.CreateTime,
            //               State = a.State,

            //           };

            //PermissonDto PermissonId = new List<int>();


        }
    }
}
